package com.xszx.controller;

import com.github.pagehelper.PageInfo;
import com.xszx.config.PageRequest;
import com.xszx.entity.User;
import com.xszx.service.UserService;
import com.xszx.utils.JWTUTIL;
import com.xszx.vo.AjaxJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/login")
    public AjaxJson login(@RequestBody Map<String, String> requestBody) {
        String username = requestBody.get("username");
        String password = requestBody.get("password");
        AjaxJson j = new AjaxJson();
        try {
            // 验证用户名和密码
            User user1 = userService.login(username,password);
            if (user1 != null) {
                // 生成token
                String token;
                token = JWTUTIL.createToken(user1.getUid());
                System.out.println("token:"+token);
                // 构造返回数据
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);

                // 构造用户信息（不包含密码）
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("id", user1.getUid());
                userInfo.put("username", user1.getLoginName());
                userInfo.put("name", user1.getName());
                userInfo.put("phone", user1.getPhone());
                userInfo.put("roleId", user1.getRid());

                data.put("userInfo", userInfo);
                j.setData(data);
                j.setErrMsg("登录成功");
                j.setSuccess("true");
                return j;
            }
            j.setCode("000");
            j.setErrMsg("用户名或密码错误");
            j.setSuccess("false");
            return j;
        } catch (Exception e) {
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping ("/register")
    public AjaxJson register(@RequestBody Map<String, String> requestBody) {
        User user = new User();
        user.setLoginName(requestBody.get("loginName"));
        user.setPassword(requestBody.get("password"));
        user.setName(requestBody.get("name"));
        user.setPhone(requestBody.get("phone"));
        AjaxJson j = new AjaxJson();
        try {
            // 检查用户名是否已存在
            if (userService.findByLoginName(user.getLoginName()) != null) {
                j.setErrMsg("用户名已存在");
                j.setSuccess("false");
                j.setCode("000");
                System.out.println("用户名已存在");
                return j;
            }
            // 注册新用户
            boolean success = userService.register(user);
            if (success) {
                j.setErrMsg("注册成功");
                j.setSuccess("true");
                return j;
            }
        } catch (Exception e) {
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping ("/info")
    public AjaxJson getUserInfo(@RequestHeader("Authorization") String token) {
        AjaxJson j = new AjaxJson();
        try {
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                // 修改这一行，从token中获取userId
                Map<String, Object> claims = JWTUTIL.checkToken(token);
                if (claims != null && claims.containsKey("userId")) {
                    String uid = claims.get("userId").toString();
                    User user = userService.findByUid(Integer.parseInt(uid));
                    if (user != null) {
                        // 清除密码
                        user.setPassword(null);
                        Map<String, Object> data = new HashMap<>();
                        data.put("user",  user);
                        j.setData(data);
                        j.setSuccess("true");
                        return j;
                    }
                }
            }
            j.setErrMsg("获取用户信息失败");
            j.setSuccess("false");
        } catch (Exception e) {
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }

    // 分页查询接口（支持多条件搜索）
    @GetMapping("/list")
    public AjaxJson getList(PageRequest pageRequest,
                            @RequestParam(defaultValue = "1") int page,    // 当前页码
                            @RequestParam(defaultValue = "10") int size) {
        pageRequest.setPage(page);
        pageRequest.setSize(size);
        System.out.println(pageRequest);
        AjaxJson j = new AjaxJson();
        try {
            PageInfo<User> pageInfo = userService.getUserListWithPage(pageRequest);
            j.put("records", pageInfo.getList());
            j.put("total", pageInfo.getTotal());
        } catch (Exception e) {
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }
    @RequestMapping("/addUser")
    public AjaxJson addUser(@RequestBody User user){
        AjaxJson j =  new AjaxJson();
        try {
            userService.addUser(user);
            j.setErrMsg("添加成功");
        }catch (Exception e){
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }

    @RequestMapping("/delUser/{id}")
    public AjaxJson delUser(@PathVariable("id") Integer id){
        AjaxJson j =  new AjaxJson();
        try {
            userService.delUser(id);
            j.setErrMsg("删除成功");
        }catch (Exception e){
            j.setErrMsg(e.getMessage());
            j.setSuccess("false");
            e.printStackTrace();
        }
        return j;
    }
    
    @RequestMapping("/updateUser")
    public  AjaxJson updateUser(@RequestBody User user){
        AjaxJson a = new AjaxJson();
        try {
            userService.updateUser(user);
            a.setErrMsg("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            a.setSuccess("false");
            a.setErrMsg("修改失败"+e.getMessage());
        }
        return a;
    }

}
